import json
import time
import app
import traceback


def main():
    try:
        print("正在加载配置...")
        config_list = app.load_config()
        print("配置加载成功，开始自动登录守护进程")

        while True:
            try:
                status_response = app.status()
                if status_response is None:
                    print("无法连接到认证服务器，10秒后重试...")
                    time.sleep(10)
                    continue

                try:
                    status_json = json.loads(status_response.text)
                except json.JSONDecodeError as e:
                    print(f"解析状态信息失败: {e}，10秒后重试...")
                    time.sleep(10)
                    continue

                if status_json.get("code") != 1:
                    app.display_status(status_json)
                else:
                    print("当前未登录，尝试自动登录...")
                    status_json = app.handle_login(config_list)
                    if status_json.get("code") == 2:
                        print("需要验证码，30分钟后重试...")
                        time.sleep(1800)  # 等待30分钟后重试
                        continue
                    elif status_json.get("code") != 1:  # 添加状态码检查
                        continue
            except Exception as e:  # 添加异常处理
                print(f"发生错误: {e}")
                traceback.print_exc()

            # 每100秒检查一次登录状态
            print("100秒后重新检查登录状态...")
            time.sleep(100)
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"程序发生严重错误: {e}")
        traceback.print_exc()
    finally:
        print("守护进程已退出")


if __name__ == "__main__":
    main()
